<template>
  <!--不合格品审理单-->
  <div  v-loading.fullscreen.lock="fullscreenLoading"></div>
  <basic-dialog v-model="dialog.showDialog" :title="dialog.title" width="1800"
                :autoClose="false" :hideFooter="true">
    <basic-crud  ref="crudRef" :option="options" :autoLoad="false"
                 v-model="formData"
                 :fastSearch="{}"
                 :before-open="beforeOpen"
                 @row-click="handleRowClick"
                 :row-save="handleAdd"
                 :row-update="handleEdit">
      <template #fileNames="{ row }">
        <el-button type="text" v-for="file in row.fileList" :key="file.id"  @click="downloadFileHandler(file)">{{
            `${file.showName}.${file.fileExtension};`
          }}</el-button>
      </template>
      <template #fileNames-form>
        <el-button type="text" v-for="file in formData.fileList" :key="file.id"  @click="downloadFileHandler(file)">{{
            `${file.showName}.${file.fileExtension};`
          }}</el-button>
      </template>
      <template #menu-right>
        <div style="display: flex;align-items: center;margin-right: 10px;">
          <span style="width: 10px;text-align: right"></span>
          <el-input v-model="fastSearchText" clearable :placeholder="'请输入编号回车查询'" size="small"
                    style="margin-right: 5px;width: 400px" @clear="fastSearchHandler"
                    @keyup.enter.native="fastSearchHandler">
            <template #suffix>
              <el-icon class="el-input__icon" style="cursor: pointer" @click="fastSearchHandler"><search /></el-icon>
            </template>
          </el-input>
        </div>
      </template>
      <template #menu-left>
        <avue-upload v-if="!onlyShow"  :showFileList="false" style="margin-left: 10px;"
                     :data="extraData"
                     :fileText="'文件上传'"
                     :action="uploadObject.action"
                     :headers="uploadObject.headers"
                     :propsHttp="uploadObject.propsHttp"
                     :upload-after="uploadAfter"
                     :upload-before="uploadBefore"
                     type="upload"
        ></avue-upload>
      </template>
      <template #menu="{ row, index }">
        <el-button v-if="row.status === 'Created'"
                   type="text"
                   icon="edit"
                   @click="crudRef.crudRef.rowEdit(row, index)"
        >编辑
        </el-button>
        <el-button v-if="!onlyShow"
                   type="danger"
                   link
                   icon="delete"
                   @click="handleDelete(row)"
        >删除
        </el-button>
      </template>
    </basic-crud>
  </basic-dialog>
</template>

<script setup>
import {defineExpose, ref} from "vue";
import { formatDate,formatMilliseconds } from "@/utils/formatTime";
import {downloadFile} from "@/utils/file.js";
import { getWorkOrder } from "@/apis/mes/processTask";
import {useUserStore} from '@/store/user';
import {ElMessage} from "element-plus";
const {token,userInfo} = useUserStore();
import {
  apiGetList,
  postAdd,
  putEdit,
  deleteDel,
} from "@/apis/mes/nonconforming.js";

const emits = defineEmits(['refresh-parent'])

const dialog = ref({
  showDialog: false,
  title: "不合格品审理单"
})

const uploadObject = ref({
  propsHttp: {
    res: "obj",
    name: "obj.name",
    url: "fileViewUrl",
  },
  headers: {
    'h-authorization-token': token
  },
  action: '/API/mes/fileController/uploadFile',
});

const parentRow = ref({});
const onlyShow = ref(false);
const doFirst = ref(false);
const searchData=ref({})

// 打开新增编辑对话框
const openDialog = (row, onlyShowValue) => {
  dialog.value.showDialog = true;
  parentRow.value=row;
  doFirst.value = false;
  onlyShow.value=onlyShowValue
  options.value.addBtn= !onlyShow.value
  options.value.menu= !onlyShow.value

  searchData.value={
    processTaskId:parentRow.value.id
  }
  getTableList()
};

const crudRef=ref(null);
const formData=ref({})
const options= ref({
  addBtn: !onlyShow.value,
  editBtn: false,
  delBtn: false,
  refreshBtn: false,
  align: "center",
  height: "570px",
  menu: !onlyShow.value,
  menuWidth: 180,
  column: [
    {
      label: "状态",
      prop: "status",
      width:80,
      sortable: true,
      sortField: "status",
      display: false,
      statusTag: true,
      statusTypeMap: {
        Auditing: 'warning',
        Released: 'success',
      }
    },
    {
      label: "编号",
      prop: "code",
      minWidth: 150,
      disabled: true,
      display: false,
    },

    {
      label: "生产部门",
      prop: "productDeptName",
      width: 100,
      display: false,
    },
    {
      label: "特性",
      prop: "peculiarityText",
      minWidth: 100,
      display: false,
      formatter: (row) => {
        let text = "";
        switch (row.peculiarity) {
          case "0":
            text = "关键特性";
            break;
          case "1":
            text = "重要特性";
            break;
          case "2":
            text = "一般特性";
            break;
        }
        return text;
      },
    },
    {
      label: "不合格情况描述",
      prop: "nonconforming",
      minWidth: 150,
      display: false,
    },
    {
      label: "不合格产生原因",
      prop: "nonReason",
      minWidth: 150,
      display: false,
    },
    {
      label: "原因分析",
      prop: "causeAnalysis",
      minWidth: 100,
      display: false,
    },
    {
      label: "纠正措施",
      prop: "rectify",
      overHidden: true,
      minWidth: 100,
      display: false,
    },
    {
      label: "型号",
      prop: "modelName",
      minWidth: 100,
      disabled: true,
      labelWidth: 120,
      display: false,
    },
    {
      label: "产品名称",
      prop: "productName",
      disabled: true,
      labelWidth: 120,
      minWidth: 100,
      display: false,
    },
    {
      label: "产品编号",
      prop: "productCode",
      overHidden: true,
      minWidth: 100,
      labelWidth: 120,
      disabled: true,
      display: false,
    },{
      label: "附件",
      prop: "fileNames",
      minWidth: 300,
      headerAlign: "center",
      align: "left",
      editDisplay:false,
      addDisplay:false,
      formslot:true,
      viewDisplay:false,
      span:24
    },
  ],
  group:[
    {
      label: "基本信息",
      prop: "jbinfo",
      labelWidth:110,
      column: [
        {
          label: "编号",
          prop: "code",
          gutter: 32,
          placeholder: "请从质量那边拿到这个编号并填写",
          span: 12,
          value: "",
        },
        {
          label: "单据状态",
          prop: "status",
          gutter: 32,
          type: "select",
          dicData: [
            {
              label: "未处理",
              value: "Created",
            },
            {
              label: "已处理",
              value: "Released",
            },
          ],
          value: "Created",
        },
        {
          label: "型号",
          prop: "modelName",
          disabled: true,
          gutter: 32,
          span: 12,
          value: "",
        },
        {
          label: "产品名称",
          prop: "productName",
          gutter: 32,
          disabled: true,
          span: 12,
          value: "",
        },
        {
          label: "产品编号",
          prop: "productCode",
          disabled: true,
          gutter: 32,
          span: 12,
          value: "",
        },
        {
          label: "交检数量",
          prop: "inspectionQuantity",
          gutter: 32,
          type: "number",
          step: 1,
          min: 1,
          rules: [{ required: true, message: "交检数量不能为空" }],
          span: 12,
          value: 0,
        },
        {
          label: "不合格数量",
          prop: "unqualifiedQuantity",
          gutter: 32,
          type: "number",
          step: 1,
          min: 1,
          rules: [{ required: true, message: "不合格数量不能为空" }],
          span: 12,
          value: 0,
        },
        {
          label: "生产部门",
          prop: "productDeptName",
          gutter: 32,
          type: "select",
          dicData: [
            {
              label: "综合室",
              value: "综合室",
            },
            {
              label: "产品技术室",
              value: "产品技术室",
            },
            {
              label: "制造工程研究室",
              value: "制造工程研究室",
            },
            {
              label: "售后室",
              value: "售后室",
            },
          ],
          rules: [{ required: true, message: "请选择生产部门" }],
          span: 12,
        },
        {
          label: "生产处特性",
          prop: "peculiarity",
          gutter: 32,
          type: "radio",
          dicData: [
            {
              label: "关键特性",
              value: "0",
            },
            {
              label: "重要特性",
              value: "1",
            },
            {
              label: "一般特性",
              value: "2",
            },
          ],
          span: 24,
          value: "0",
        },
        {
          label: "发现时机",
          prop: "findMoment",
          gutter: 32,
          type: "radio",
          dicData: [
            {
              label: "入所复检",
              value: "0",
            },
            {
              label: "工序交检",
              value: "1",
            },
            {
              label: "出所交检",
              value: "2",
            },
            {
              label: "用户代表检查",
              value: "3",
            },
            {
              label: "生产自查",
              value: "4",
            },
            {
              label: "其他",
              value: "5",
            },
          ],
          span: 24,
          value: "0",
        },
        {
          label: "创建时间",
          prop: "proposeTime",
          type: "datetime",
          value: formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"),
          gutter: 32,
          formatter: (row) => {
            return formatDate(row.proposeTime, "yyyy-MM-dd HH:mm:ss");
          },
        },
        {
          label: "完成时间",
          prop: "zeroingTime",
          type: "datetime",
          value: formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"),
          gutter: 32,
          formatter: (row) => {
            return formatDate(row.zeroingTime, "yyyy-MM-dd HH:mm:ss");
          },
        },
      ],
    },
    {
      label: "不合格内容",
      prop: "jbinfos",
      column: [
        {
          label: "图纸，技术条件要求",
          prop: "technicalRequirements",
          type: "textarea",
          labelPosition: "top",
          gutter: 32,
          minRows: 3,
          maxRows: 5,
          span: 24,
          value: "",
        },
        {
          label: "处理措施",
          prop: "solution",
          type: "textarea",
          labelPosition: "top",
          gutter: 32,
          minRows: 3,
          maxRows: 5,
          span: 24,
          value: "",
        },
        {
          label: "不合格情况描述",
          prop: "nonconforming",
          type: "textarea",
          labelPosition: "top",
          gutter: 32,
          minRows: 3,
          maxRows: 5,
          span: 24,
          value: "",
        },
        {
          label: "不合格品产生原因",
          prop: "nonReason",
          type: "textarea",
          labelPosition: "top",
          gutter: 32,
          minRows: 3,
          maxRows: 5,
          span: 24,
          value: "",
        },
        {
          label: "原因分析",
          prop: "causeAnalysis",
          type: "textarea",
          labelPosition: "top",
          gutter: 32,
          minRows: 3,
          maxRows: 5,
          span: 24,
          value: "",
        },
        {
          label: "纠正措施",
          prop: "rectify",
          type: "textarea",
          labelPosition: "top",
          gutter: 32,
          minRows: 3,
          maxRows: 5,
          span: 24,
          value: "",
        },
        {
          label: "附件",
          prop: "fileNames",
          minWidth: 300,
          editDisplay:false,
          addDisplay:false,
          formslot:true,
          viewDisplay:true,
          span:24
        }
      ],
    },
  ]
})

const fullscreenLoading = ref(false)
const getTableList=()=> {
  fullscreenLoading.value = true
  apiGetList(searchData.value,fullscreenLoading).then((res) => {
    if (res.success) {
      if (!onlyShow.value && res.total == 0 && !doFirst.value) {
        crudRef.value.crudRef.rowAdd();
      }else {
        doFirst.value = true;
        crudRef.value.tableData = res.data;
        crudRef.value.pageData.total = res.total;
      }
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(() => {ElMessage.error("获取列表数据失败!")});
}

const fastSearchText=ref('')
//多属性快速查询
const fastSearchHandler=()=> {
  if(fastSearchText.value){
    searchData.value={
      processTaskId: parentRow.value.id,
      fastColumn:'code',
      fastText:fastSearchText.value
    }
  }else{
    searchData.value={
      processTaskId: parentRow.value.id
    }
  }
  getTableList();
}

const currentRow=ref(null);
const extraData=ref({})
const handleRowClick=(row) =>{
  currentRow.value=row
  extraData.value={
    ownId:row.id,
    ownBus:row.bus
  }
}

const uploadBefore=(file, done, loading)=> {
  if (!extraData.value.ownId) {
    ElMessage.error("请先点击行数据选中一条不合格品审理单信息！");
    loading();
  } else {
    done();
  }
}
//上传后事件
const uploadAfter=(res, done, loading)=> {
  ElMessage.success("上传成功！");
  getTableList();
  loading();
  done();
  extraData.value={}
}

const beforeOpen=(done, type)=> {
  if (type == "add") {
    //先从后台获取下工单的信息，用于显示产品等几个属性
    getWorkOrder(parentRow.value.id).then((obj) => {
      if (
          !obj.pdmProductCode ||
          obj.pdmProductCode == null ||
          obj.pdmProductCode == ""
      ) {
        return ElMessage.error("任务的产品编号都还没有添加，请先执行开工");
      }
      formData.value.modelName = obj.modelName;
      formData.value.processTaskId = parentRow.value.id;
      formData.value.productId = obj.pdmProduct;
      formData.value.productName = obj.pdmProductName;
      formData.value.productCode = obj.pdmProductCode;
      done();
    });
  } else if (type == 'edit') {
    if (formData.value.status === "Released") {
      return ElMessage.error("已经处理完成的单据，不能再修改了");
    } else {
      done();
    }
  } else {
    done();
  }
}
// 新增
const handleAdd=(form, done, loading)=> {
  form.proposeTime = formatMilliseconds(new Date(form.proposeTime));
  if (typeof form.zeroingTime === "object" && form.zeroingTime instanceof Date) {
    form["zeroingTime"] = formatMilliseconds(form.zeroingTime);
  } else if (typeof form.zeroingTime === "string") {
    form["zeroingTime"] = formatMilliseconds(new Date(form.zeroingTime));
  }
  postAdd(form).then((res) => {
    ElMessage.success("新增数据成功!");
    refreshHandler();
  }).finally((res) => {
    loading()
    done(form);
  });
}
// 编辑
const handleEdit=(form, index, done, loading)=> {
  form.proposeTime = formatMilliseconds(new Date(form.proposeTime));
  if (typeof form.zeroingTime === "object" && form.zeroingTime instanceof Date) {
    form["zeroingTime"] = formatMilliseconds(form.zeroingTime);
  } else if (typeof form.zeroingTime === "string") {
    form["zeroingTime"] = formatMilliseconds(new Date(form.zeroingTime));
  }
  putEdit(form).then((res) => {
    ElMessage.success("修改数据成功!");
    getTableList();
    done(form);
  }).finally((res) => {
    loading()
    done(form);
  });
}

// 删除
const handleDelete=(row)=> {
  if (row.status != "Created") {
    return ElMessage.success("当前状态不允许删除");
  }
  ElMessageBox.confirm(`此操作将永久删除数据, 是否继续?`, "提示").then(() => {
    deleteDel(row.id).then((res) => {
      ElMessage.success("删除成功");
      doFirst.value = true;
      refreshHandler();
    });
  }).catch(() => {
  });
}

//文件下载
const downloadFileHandler=async (row)=> {
  downloadFile(row.id, row.name, "/mes");
}
const refreshHandler=()=> {
  getTableList();
  emits('refresh-parent')
}

defineExpose({
  openDialog
})
</script>

<style scoped>

</style>